// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

mod commands;
mod config;
mod crawler;
mod database;
mod error;
mod models;
mod utils;

use crate::config::AppConfig;
use crate::database::Database;
use std::sync::Arc;
use tauri::Manager;
use tokio::sync::Mutex;

pub struct AppState {
    pub config: Arc<Mutex<AppConfig>>,
    pub database: Database,
}

#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .setup(|app| {
            // 初始化应用状态
            let rt = tokio::runtime::Runtime::new().unwrap();
            let config = rt.block_on(async {
                AppConfig::load().await.unwrap_or_default()
            });
            let database = rt.block_on(async {
                match Database::new().await {
                    Ok(db) => db,
                    Err(e) => {
                        eprintln!("数据库初始化失败: {}", e);
                        // 创建一个简单的内存数据库作为后备
                        Database::new_memory().await.unwrap_or_else(|_| {
                            panic!("无法创建内存数据库")
                        })
                    }
                }
            });
            
            let state = AppState {
                config: Arc::new(Mutex::new(config)),
                database,
            };
            
            app.manage(state);
            Ok(())
        })
        .invoke_handler(tauri::generate_handler![
            greet,
            commands::get_config,
            commands::update_config,
            commands::save_config,
            commands::reset_config,
            commands::start_crawler,
            commands::pause_crawler,
            commands::stop_crawler,
            commands::get_crawler_status,
            commands::get_data_overview,
            commands::get_data_list,
            commands::export_data,
            commands::delete_data,
            commands::get_logs,
            commands::get_python_logs,
            commands::clear_logs,
            commands::export_logs,
            commands::get_statistics,
            commands::get_platform_stats,
            commands::get_system_info,
            commands::open_data_folder,
            commands::check_for_updates,
            commands::select_folder,
            commands::select_file,
            commands::save_file,
            // 任务相关命令
            commands::submit_task,
            commands::get_task_list,
            commands::get_task_by_id,
            commands::pause_task,
            commands::resume_task,
            commands::stop_task,
            commands::get_task_logs,
            commands::export_task_logs
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

fn main() {
    run();
}